<?php

/**
 * This is the model class for table "{{category}}".
 *
 * The followings are the available model relations:
 * @property Category $category
 */
class Category extends CActiveRecord
{
	public $post_count;

	/**
	 * Tree level, starting from 0
	 *
	 * @var int
	 */
	public $level;

	/**
	 * Returns the static model of the specified AR class.
	 * @param string $className active record class name.
	 * @return Category the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return '{{category}}';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
			array('name', 'required', 'on'=>'adminCreate, adminUpdate'),
			array('parent_category_id', 'numerical', 'integerOnly'=>true),
			array('name', 'length', 'max'=>200),
			array('name, path, parent_category_id, position', 'safe'),
			// The following rule is used by search().
			// Please remove those attributes that should not be searched.
			array('id, name, path, parent_category_id,post_count', 'safe', 'on'=>'search'),
		);
	}

	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
			'post' => array(self::HAS_MANY, 'Post', 'category_id'),
			'parentCategory' => array(self::BELONGS_TO, 'Category', 'parent_category_id'),
			'childCategories' => array(self::HAS_MANY, 'Category', 'parent_category_id'),
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'parent_category_id' => 'Parent'
		);
	}

	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
	 */
	public function search()
	{
		$cats = array();
		self::buildCategoryData($cats);
		return new CArrayDataProvider($cats, array(
			'id'=>'category',
			'sort'=>false,
			'pagination'=>false,
		));
	}
	
	public function getIndent() {
		return str_repeat('&nbsp;&nbsp;&nbsp;&nbsp;', $this->level);
	}
	
	public function getParentCategoryListData() {
		$cats = array();
		self::buildCategoryData($cats, null, 0, $this->id);
		$result = array();
		foreach($cats as $cat) {
			$result[$cat->id] = $cat->getIndent().$cat->name;
		}
		return $result;
	}

	public static function buildCategoryData(&$arr, $parentCatId=null, $level=0, $exclude=null) {
		foreach(self::getChildCategories($parentCatId, $exclude) as $cat) {
			$cat->level = $level;
			$arr[] = $cat;
			self::buildCategoryData($arr, $cat->id, $level+1, $exclude);
		}
	}
	
	public static function getChildCategories($parentId=null, $exclude=null) {
		$p = Post::model()->tableName();
		$criteria = new CDbCriteria;
		$criteria->order = 'position';
		$criteria->select = 't.*, count(p.id) AS post_count';
		$criteria->join = "LEFT JOIN $p p ON t.id=p.category_id";
		$criteria->group = "t.id";
		
		if ($parentId)
			$criteria->compare('parent_category_id',$parentId);
		else
			$criteria->addCondition('parent_category_id is NULL');

		if ($exclude)
			$criteria->addCondition("t.id!=$exclude");

		return self::model()->findAll($criteria);
	}
	
	protected static $_categories = null;	// caching all category models
	
	public function getPathName() {
		// caching prepare
		if (!self::$_categories) {
			self::$_categories = array();
			$cats = self::model()->findAll();
			foreach ($cats as $c) {
				self::$_categories[$c->id] = $c;
			}
		}
		
		$items = array();
		$item = $this;
		while ($item) {
			$items[] = $item->name;
			$item = isset(self::$_categories[$item->parent_category_id]) ? self::$_categories[$item->parent_category_id] : null;
		}
		return implode(' &#187; ', array_reverse($items));
	}
	
}